import traceback
from flask import Blueprint,render_template,jsonify,request,render_template_string
from sqlalchemy import func, and_
from werkzeug.utils import send_from_directory
import  models
import json
from werkzeug.serving import WSGIRequestHandler
WSGIRequestHandler.protocol_version = "HTTP/1.1"
import os
import config
from config import PROTOTYPE_JS, debug, log as log
from config import makeNewSession as makeNewSession
from uuid import uuid4
from datetime import datetime,timedelta

form = Blueprint('form',__name__)

# 创建自定义表单
@form.route("/createForm", methods=["POST"])
def createForm():
    try:
        getData = request.get_json()
        if not getData: return "you need post some args!",406

        session = makeNewSession()
        serverFileName = f"{uuid4()}.html"
        form = models.Form(formTitle=getData['title'],
            serverFileName=serverFileName,
            dbs_fields=getData['dbs_fields'])
        session.add(form)
        session.commit()

        # print("get form id", form.formID)
        with open(config.FORMPROTOTYPE, 'r', encoding='utf8') as f:
            html = f.read()
        html = html.format(layui_css=config.LAYUI_CSS_PATH, 
        layui_js=config.LAYUI_JS_PATH, 
        axios_js=config.AXIOS_PATH,
        tableSelect_js=config.TABLESELECT_JS,
        page_title=getData['title'],
        form_title=getData['title'],
        form_description=getData['description'],
        body_content=getData['body_content'],
        prototype_js=config.PROTOTYPE_JS,
        form_id=form.formID,
        tableID="{{tableID}}")

        with open(os.path.join(config.FORMDIR, serverFileName), 'w+', encoding='utf8') as f:
            f.write(html)


        session.close()
        return "createForm ok"
    except:
        traceback.print_exc()
        session.rollback()
        session.close()
        return "createForm fail",500
    




# 页面打开 自定义表单 
@form.route("/getForm")
def getForm():
    session = makeNewSession()
    id_ = request.args.get('id', type=int)
    tableID = request.args.get('tableID', type=int)
    q = session.query(models.Form).filter(models.Form.formID==id_).first()
    if not q:
        return render_template("404.html"),404
    path = os.path.join(config.FORMDIR, q.serverFileName)
    if not os.path.exists(path):
        return render_template("404.html"),404
    with open(path, 'r', encoding='utf8') as f:
        html = f.read()
    # print(html)
    return render_template_string(html,tableID=tableID)


# 删除表单
@form.route("/delFormData",methods=["POST"])
def delFormData():
    getData = request.get_json()
    if not getData: return "you need post some args!",406
    session = makeNewSession()
    try:
        q = session.query(models.Form).filter(models.Form.formID==getData['formID']).first()
        fPath = os.path.join(config.FORMDIR,q.serverFileName)
        # print("fPath", fPath)
        if os.path.exists(fPath):
            os.remove(fPath)
        session.delete(q)
        session.commit()
        session.close()
        return "del successfully"
    except:
        traceback.print_exc()
        session.rollback()
        session.close()
        return "del failure",500

# 删除表单 多
@form.route("/delFormsData",methods=["POST"])
def delFormsData():
    getDatas = request.get_json()
    # print(getDatas)
    session = makeNewSession()
    try:
        qs = session.query(models.Form).filter(models.Form.formID.in_(getDatas))
        for each in qs:
            fPath = os.path.join(config.FORMDIR,each.serverFileName)
            # print("fPath", fPath)
            if os.path.exists(fPath):
                os.remove(fPath)
            
        qs.delete()
        session.commit()
        session.close()
        return "del successfully"
    except:
        session.rollback()
        session.close()
        return "del failure",500



# 获取创建的表单数据
@form.route("/formData")
def formData():
    curPage = request.args.get("page",1,type=int)
    per_page = request.args.get("limit",15,type=int)
    getData = json.loads(request.args.get("searchParams","{}"))
    # print(getData, bool(getData),"text",getData)
    session = makeNewSession()
    if getData:
        stime = getData.get("datetime",None)
        if not stime: stime = f"2022-01-03 - {(datetime.now()+timedelta(4)).date()}"
        stime  = stime.split(" - ") 
        print("stime",stime)
        condition = and_(
            models.Form.formTitle.contains(getData.get("formTitle", '')) if getData.get("formTitle", '') else True,
            models.Form.beizhu.contains(getData.get("beizhu", '') ) if getData.get("beizhu", '') else True,
            models.Form.datetime >= stime[0],
            models.Form.datetime <= stime[1]
        )

    # 分页
    all_ = session.query(models.Form).offset((curPage-1)*per_page).limit(per_page)   if not getData else session.query(models.Form).filter(condition).offset((curPage-1)*per_page).limit(per_page)  

    # count  = session.query(func.count(all_)).scalar()
    # 获取总条数
    count =session.query(func.count(models.Form.formID)).scalar() if not getData else session.query(func.count(models.Form.formID)).filter(condition).scalar()

    result = {
        "code": 0,
        "msg": "",
        "count": count,
        "data": []
        }
    debug("all_",all_)
    for each in all_:
        result['data'].append(each.to_json())
    session.close()
    return jsonify(result)



# 更新表单信息
@form.route("/updateFormData",methods=["POST"])
def updateFormData():
    getData = request.get_json()
    if not getData: return "you need post some args!",406
    print(getData)
    session = makeNewSession()
    try:
        session.query(models.Form).filter(models.Form.formID==getData["formID"]).update(getData)
        session.commit()
        session.close()
        return "update successfully"
    except:
        session.rollback()
        session.close()
        return "update failure",500